package com.kushe.site.controller;

import com.kushe.dao.*;
import com.kushe.entity.*;
import com.kushe.site.form.GroupForm;
import com.kushe.util.KSController;
import com.kushe.util.core.DaoFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.nutz.dao.QueryResult;
import org.nutz.json.Json;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * Created by WSDevotion on 2015/5/2.
 */
@Controller
@RequestMapping("/group")
public class GroupController extends KSController{
    //打开小组页面
    @RequestMapping("goGroups")
    public Object goGroups(HttpServletRequest request, Model model) {
        //从session中User

        //判断用户是否在小组中
        User user = (User) request.getSession().getAttribute("user");
        int id = user.getId();
        List<UserAndGroup> list = UserAndGroupDao.getUserAndGroupByuser_id(user.getId());
        //小组为空返回小组页面
        if (list.size() == 0) {
            this.setAttr("page1", GroupDao.listByHot(1, 1));
            this.setAttr("page2", GroupDao.listByHot(1, 2));
            this.setAttr("page3", GroupDao.listByHot(1, 3));
            return this.render("group/pregroup.html");
        }

        //小组不为空返回小组话题页面
        int[] groups = new int[list.size()];
        int i = 0;
        for (UserAndGroup userAndGroup : list) {
            groups[i] = userAndGroup.getGroup_id();
            i++;
        }
        //找到用户小组信息
        List<Group> groups1 = new LinkedList<Group>();
        for (int j : groups) {
            groups1.add(GroupDao.get(j));
        }
        //获取用户创建的小组
        List<Group> groups2 = GroupDao.getGroupByUser_id(id);
        //获取我发的帖子
        List<Topics> topicses = TopicsDao.getTopicsByUser_id(id);
        //获取我参与回复的帖子
        List<Comment> comments = CommentDao.getCommentByUser_id(id);
        List<Topics> huifu_Topics = new LinkedList<Topics>();
        int[] huifu = new int[comments.size()];
        int k = 0;
        for (Comment comment : comments) {
            int f = 1;
            for (i = 0; i < huifu.length; i++) {
                if (huifu[i] == comment.getTopic_id()) {
                    f = 0;
                    break;
                }
            }
            if (f == 1) {
                huifu[k] = comment.getTopic_id();
                k++;
                Topics t = TopicsDao.get(comment.getTopic_id());
                huifu_Topics.add(t);
            }
        }
        this.setAttr("huifu_Topics", huifu_Topics);
        this.setAttr("topicses", topicses);
        this.setAttr("create_group", groups2);
        this.setAttr("groups", groups1);

        return this.render("group/messege.html");
    }


    @RequestMapping("togroup")
    public Object togroup() {
        return this.render("group/create.html");

    }

    //查找小组主页
    @RequestMapping("getGroup")
    public Object getGroupByid(@RequestParam(value = "group_id", defaultValue = "1", required = false) int group_id, Model model, HttpServletRequest request) {
        Group group = GroupDao.get(group_id);
        if (group == null) {
            System.out.println("error");
            return "";
        }
        this.setAttr("hotGroup", GroupDao.listByHot(1, Integer.parseInt(group.getType())));
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        this.setAttr("username", user.getName());
        this.setAttr("group", group);
        int[] groups = {group_id};
        this.setAttr("topics", TopicsDao.getByTime(1, groups));
        this.setAttr("topicshot", TopicsDao.getByHot(1, groups));
        this.setAttr("message", "");

        return this.render("group/team-home.html");
    }

    //加入多个小组
    @RequestMapping("addGroupsall")
    public Object addGroupsall(String groupSelect, HttpServletRequest request) {
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        String[] groups = groupSelect.split("&");
        UserAndGroup group = null;
        for (String g : groups) {
            group = new UserAndGroup();
            Group g1 = GroupDao.get(Integer.parseInt(g));
            g1.setNum(g1.getNum() + 1);
            GroupDao.updateGroup(g1);
            group.setUser_id(user.getId());
            group.setGroup_id(Integer.parseInt(g));
            UserAndGroupDao.addUserAndGroup(group);
        }
        return this.render("redirect:/group/goGroups");

    }

    //精选话题
    @RequestMapping("toHotTopic")
    public Object toHotTopic(@RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "type", defaultValue = "0") int type, HttpServletRequest request) {
        //获取话题
        int[] group_id = null;
        if (type == 0) {
            group_id = new int[2];
            group_id[0] = 0;
        } else {
            List<Group> list = GroupDao.getBytype(type);
            group_id = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                group_id[i] = list.get(i).getId();
            }
        }


        QueryResult topics = TopicsDao.getByHot(page, group_id);
        this.setAttr("topicsHot", topics);
        //model.addAttribute("topicsHot", topics);
        //判断用户是否点赞
        List<Topics> list = (List<Topics>) topics.getList();
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        for (int i = 0; i < list.size(); i++) {
            Sign s = SignDao.getSigns(user.getId(), list.get(i).getId());
            if (s != null) {
                ((List<Topics>) topics.getList()).get(i).setState(1);
            }
        }
        //获取小组
        QueryResult groups = GroupDao.listByHot(1, 0);
        List<Group> listgroup = (List<Group>) groups.getList();
        List<Group> listr = new LinkedList<Group>();
        for (Group g : listgroup) {
            List<UserAndGroup> list3 = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), g.getId());
            if (list3.size() == 0) {
                listr.add(g);
            }
        }
        int i = 2;
        while (listr.size() < 5) {
            QueryResult q = GroupDao.listByHot(i, 0);
            List<Group> list1 = (List<Group>) q.getList();
            if (i == q.getPager().getPageCount()) {
                break;
            }
            for (Group g : list1) {
                List<UserAndGroup> list2 = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), g.getId());
                if (list2.size() == 0) {
                    listr.add(g);
                }
            }
            i++;
        }
        this.setAttr("type", type);
        this.setAttr("group", listr);
        return this.render("group/classified-team-view.html");

    }



    //进入小组页面
    @RequestMapping("/toGroupindex")
    public Object toGroup(int id, HttpServletRequest request) {
        //通过id查找小组
        Group group = GroupDao.get(id);
        //model.addAttribute("hotGroup", GroupDao.listByHot(1, Integer.parseInt(group.getType())));
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        this.setAttr("username", user.getName());
        this.setAttr("group", group);
        //判断用户加入的小组
        QueryResult groups = GroupDao.listByHot(1, Integer.parseInt(group.getType()));
        List<Group> listgroup = (List<Group>) groups.getList();
        List<Group> listr = new LinkedList<Group>();
        for (Group g : listgroup) {
            List<UserAndGroup> list3 = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), g.getId());
            if (list3.size() == 0) {
                listr.add(g);
            }
        }
        int i = 2;
        while (listr.size() < 5) {
            QueryResult q = GroupDao.listByHot(i, Integer.parseInt(group.getType()));
            List<Group> list1 = (List<Group>) q.getList();
            if (i == q.getPager().getPageCount()) {
                break;
            }
            for (Group g : list1) {
                List<UserAndGroup> list2 = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), g.getId());
                if (list2.size() == 0) {
                    listr.add(g);
                }
            }
            i++;
        }
        this.setAttr("hotGroup", listr);
        //判断用户是否已经加入小组
        List<UserAndGroup> list = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), group.getId());
        if (list.size() != 0) {
            //用户已经加入小组
            this.setAttr("isGroups", "1");
        } else {
            this.setAttr("isGroups", "0");
        }
        int[] g = {group.getId()};
        this.setAttr("topics", TopicsDao.getByTime(1, g));
        this.setAttr("topicshot", TopicsDao.getByHot(1, g));
        this.setAttr("message", "");
        GroupDao.addGroup(group);
        return this.render("group/team-home.html");
    }



    //创建小组
    @RequestMapping("addGroup")
    public Object addGroup(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Group group) {
        GroupForm form = new GroupForm();
        if (!form.validate(request)) {
            System.out.println("表单");
            return "error";
        }
        //判断是否重名
        Group groups = GroupDao.getGroupByName(group.getName());
        if (groups != null) {
            System.out.println("名字重复");
            this.setAttr("error", "名字重复");
            //model.addAttribute("error", "名字重复");
            return "group/create.html";
        }
        //上传图片
        String filename = uploadImg(file, request);

        //上传信息


        group.setImageurl("\\upload\\" + filename);
        //path = path + "\\" + filename;
        Date date = new Date();
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        group.setGroup_time(date);
        group.setCreater_id(user.getId());

        Group group1 = GroupDao.addGroup(group);
        UserAndGroup userAndGroup = new UserAndGroup();
        userAndGroup.setGroup_id(group1.getId());
        int[] g = {group1.getId()};
        userAndGroup.setUser_id(user.getId());
        UserAndGroupDao.addUserAndGroup(userAndGroup);

        return this.render("redirect:/group/toGroupindex?id=" + group1.getId());
    }

    //--------------------------------------------返回json

    //话题主页分页
    @RequestMapping(value = "getTopicByweb", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getTopicByweb(int group_id, int page) {
        Group group = GroupDao.get(group_id);
        JSONObject json = new JSONObject();
        if (group == null) {
            System.out.println("error");
            json.put("success", "0");
            return json;
        }

        int[] groups = {group_id};
        List<Topics> list1 = (List<Topics>) TopicsDao.getByTime(page, groups).getList();
        JSONArray a = new JSONArray();
        JSONObject json1 = new JSONObject();
        for (Topics g : list1) {
            String j = Json.toJson(g);
            a.add(j);
        }
        json1.put("getTime", a);
        List<Topics> list2 = (List<Topics>) TopicsDao.getByHot(page, groups).getList();
        for (Topics g : list2) {
            String j = Json.toJson(g);
            a.add(j);
        }
        json1.put("getHot", a);
        json1.put("success", "1");
        return json1;
    }

    //加入小组
    @RequestMapping("intoGroup")
    @ResponseBody
    public Object intoGroup(int group_id, HttpServletRequest request) {
        //通过小组id查询小组信息
        Group group = GroupDao.get(group_id);
        //通过用户id查询用户
        //----------------------------
        UserDao userDao = DaoFactory.getDao(UserDao.class);
        //从session中得到user
        User user = (User) request.getSession().getAttribute("user");
        //User user = userDao.get(u.getId());
        //判断小组和用户
        JSONObject json = new JSONObject();
        if (group == null || user == null) {
            json.put("success", "0");
            return json;
        }
        //查询用户是否已经加入小组
        List<UserAndGroup> list = UserAndGroupDao.getMesByuser_idAndGroup_id(user.getId(), group_id);
        if (list.size() != 0) {
            json.put("success", "-1");
            return json.toString();
        }
        UserAndGroup userAndGroup = new UserAndGroup();
        userAndGroup.setUser_id(user.getId());
        userAndGroup.setGroup_id(group_id);
        UserAndGroupDao.addUserAndGroup(userAndGroup);
        json.put("success", "1");
        return json;
    }
}
